package com.twentytwok.hospitalsystem22K.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;


public class QiNiuUtils2 {
    public static String accessKey="Q0I84d9mT8UlKbUoUUR21r7pzMlwyxJwtKvPponj";
    public static String secretKey="OSyDaJlB2AQrrJTNbyUUc4M0Ld0moLNbz8ANyyeQ";
    public static String bucket="ssm11";

    public static void uploadByQiniu(byte[] bytes,String uploadFileName){

        Configuration cfg = new Configuration(Region.region2());

        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(accessKey, secretKey);

        String upToken = auth.uploadToken(bucket);
        Response response = null;
        try {
            response = uploadManager.put(bytes, uploadFileName, upToken);

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);

        } catch (QiniuException e) {
            Response r = e.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    @Test
    public void test1() throws IOException {
        byte[] bytes = FileUtils.readFileToByteArray(new File("C:\\Users\\Lenovo\\Pictures\\Saved Pictures\\aa.png"));

        uploadByQiniu(bytes,"ff.png");
    }

}
